// vue.config.js 是脚手架的配置文件; 修改了必须重启项目
// 使用js的严格模式， 注意：严格模式下 this如果指向undefined，说明指向window
'use strict'

// 导入nodejs的path模块
const path = require('path')
// 导入src下面的settings.js的配置
const defaultSettings = require('./src/settings.js')
//  将相对路径转为绝对路径
function resolve(dir) {
  return path.join(__dirname, dir)
}
// 定义网页的标题
const name = defaultSettings.title || '悦兴物业综合服务平台' // page title

// 设置项目运行的端口(读取环境变量里面的prot，如果没有读取packagejson里面的port，如果还没有使用9528)
const port = process.env.port || process.env.npm_config_port || 8888 // dev port
const isProd = process.env.NODE_ENV === 'production'

// ===> CDN资源设置 START
let externals = {
  externals: {

    // key(要排除的包名), value(引入的CDN包的全局变量名)
    'vue': 'Vue',
    'element-ui': 'ELEMENT',
    'xlsx': 'XLSX',
    'echarts': 'echarts',
    'vue-quill-editor': 'VueQuillEditor',
    'axios': 'axios',
    // 'vue-router': 'VueRouter',
    'vuex': 'Vuex'
  }
}
let cdn = {
  css: [

  ], // css的cdn资源网址
  js: [

  ] // js的cdn资源网址
}
if (isProd) {
  externals = {
    // 键：值 【比较难的事情就是找对应版本的cdn资源文件；和该文件在全局的变量名称】
    // 键是包名, 值是该包在全局window下面(index.html)里面的全局变量名称
    'echarts': 'echarts',
    'xlsx': 'XLSX',
    'element-ui': 'ELEMENT',
    'vue': 'Vue',
    'vue-quill-editor': 'VueQuillEditor',
    'mockjs': 'Mock',
    'vue-router': 'VueRouter',
    'vuex': 'Vuex',
    'vue-amap': 'VueAmap',
    'axios': 'axios'
  }

  cdn = {
    css: [
      'https://cdn.jsdelivr.net/npm/quill@1.3.7/dist/quill.core.css',
      'https://cdn.jsdelivr.net/npm/quill@1.3.7/dist/quill.snow.css',
      'https://cdn.jsdelivr.net/npm/quill@1.3.7/dist/quill.bubble.css',
      'https://unpkg.com/element-ui/lib/theme-chalk/index.css' // element-ui css 样式表
    ],
    js: [
      'https://unpkg.com/element-ui/lib/index.js', // element-ui js
      'https://cdn.bootcdn.net/ajax/libs/echarts/4.0.4/echarts.min.js',
      'https://cdn.bootcdn.net/ajax/libs/xlsx/0.18.5/xlsx.mini.min.js',
      'https://cdn.jsdelivr.net/npm/xlsx@0.16.6/dist/jszip.min.js',
      'https://cdn.jsdelivr.net/npm/xlsx@0.16.6/dist/xlsx.full.min.js',
      'https://unpkg.com/quill@1.3.7/dist/quill.js',
      'https://unpkg.com/vue-quill-editor@3.0.6/dist/vue-quill-editor.js',
      'https://unpkg.com/vue@2.6/dist/vue.min.js',
      'https://unpkg.com/vue-router@3.5.4/dist/vue-router.js',
      'https://unpkg.com/axios@0.27.2/dist/axios.min.js',
      'https://unpkg.com/vuex@3.6.2/dist/vuex.js',
      'https://cdn.bootcss.com/Mock.js/1.0.1-beta3/mock-min.js',
      'https://cdn.jsdelivr.net/npm/echarts/map/js/china.js?v=1598903772045',
      'https://unpkg.com/vue-amap/dist/index.js',
      'https//cdn.jsdelivr.net/npm/echarts@4.8.0/map/js/china.js',
      'https://lib.baomitu.com/core-js/3.27.1/minified.min.js'
    ]
  }
}
// ===> CDN资源设置 END

// 定义配置  https://cli.vuejs.org/config/
module.exports = {
  // 资源引用路径
  publicPath: isProd ? './' : '/',
  // 打包输出目录
  outputDir: 'dist',
  // 打包静态文件目录
  assetsDir: 'static',
  // 是否开启代码校验
  lintOnSave: process.env.NODE_ENV === 'development',
  // 是否关闭map文件
  productionSourceMap: false, // 把这边的true改为false
  // https://webpack.js.org/configuration/devtool/#production
  // devtool: '#source-map',

  // 开发服务器介绍
  devServer: {
    port: port, // 端口号
    open: false, // 运行好了之后是否自动打开浏览器
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      // /api 表示 所有请求地址都有的公共
      // http://ihrm-java.itheima.net 表示需要代理的请求地址
      '/admin': {
        target: 'http://124.223.14.236:8881'
      }
    }
    // proxy要么写配置，不允许空着
    // proxy: {
    //   /*
    //    '/地址':{
    //       target:"跨域目标地址",
    //       changeOrigin:true  // 是否需要跨域
    //       pathRewrite:{   // 路径是否重写
    //         '^/地址': ''
    //       }
    //    }
    //    */
    // },
  },
  // webpack的配置【对象式配置】
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name, // 网页标题
    resolve: {
      // 路径解析
      alias: {
        '@': resolve('src') // 如果遇到@src进行解析为根目录的scr目录
      }
    },
    // webpack打包的时候会排除的内容
    externals: externals
  },
  // webpack的配置【函数式配置】
  chainWebpack(config) {
    // 配置html-webpack-plugins插件，注入cdn资源
    config.plugin('html').tap((args) => {
      args[0].cdn = cdn // 相当于在index.html里面有个变量叫做cdn
      return args
    })
    // it can improve the speed of the first screen, it is recommended to turn on preload
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])
    // 注入cdn变量 (打包时会执行)
    config.plugin('html').tap(args => {
      args[0].cdn = cdn // 配置cdn给插件
      return args
    })

    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete('prefetch')

    // set svg-sprite-loader
    config.module.rule('svg').exclude.add(resolve('src/icons')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config.when(process.env.NODE_ENV !== 'development', (config) => {
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/
          }
        ])
        .end()
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // only package third parties that are initially dependent
          },
          elementUI: {
            name: 'chunk-elementUI', // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      })
      // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
      config.optimization.runtimeChunk('single')
    })
  }
}
